package com.sy.msgview

import android.app.Activity
import android.content.Context
import android.content.pm.PackageManager
import android.net.Uri
import android.util.Log
import androidx.core.app.ActivityCompat
import okhttp3.Call
import okhttp3.Callback
import okhttp3.FormBody
import okhttp3.OkHttpClient
import okhttp3.Request
import okhttp3.RequestBody
import okhttp3.Response
import java.io.FileOutputStream
import java.io.IOException


object Utils {
	private val client by lazy { OkHttpClient() }

	enum class LogLevel {
		VERBOSE,
		DEBUG,
		INFO,
		WARN,
		ERROR,
		ASSERT
	}

	fun showLog(log: Any?, tag: String = "SYTAG", level: LogLevel = LogLevel.VERBOSE) {
		val current = Throwable().stackTrace[2]
		val fileName = current.fileName
		val lineNumber = current.lineNumber
		val decorLog = "($fileName:$lineNumber) ===> ${log.toString()}"
		when (level) {
			LogLevel.VERBOSE -> Log.v(tag, decorLog)
			LogLevel.DEBUG -> Log.d(tag, decorLog)
			LogLevel.INFO -> Log.i(tag, decorLog)
			LogLevel.WARN -> Log.w(tag, decorLog)
			LogLevel.ERROR -> Log.e(tag, decorLog)
			LogLevel.ASSERT -> Log.wtf(tag, decorLog)
		}

	}

	fun getDatabase(context: Context, database: String = "backup.db", override: Boolean = false): String {
		val databasePath = context.getDatabasePath(database)
		if (!databasePath.exists() || override) {
			try {
				val inputStream = context.assets.open(database)
				val outputStream = FileOutputStream(databasePath)

				val buffer = ByteArray(1024)
				var length: Int
				while (inputStream.read(buffer).also { length = it } > 0) {
					outputStream.write(buffer, 0, length)
				}
				outputStream.flush()
				outputStream.close()
				inputStream.close()
			} catch (e: IOException) {
				e.printStackTrace()
			}
		}

		return databasePath.path
	}


	@Throws(IOException::class)
	fun getRequest(
		url: String,
		method: String = "GET",
		requestBody: RequestBody = FormBody.Builder().build(),
		callback: (Response) -> Unit
	) {
		val request = Request.Builder().let {
			it.url(url)
			when (method.uppercase()) {
				"GET" -> it.get()
				"POST" -> it.post(requestBody)
				else -> {}
			}
			it.build()
		}

		client.newCall(request).enqueue(object : Callback {
			override fun onFailure(call: Call, e: okio.IOException) {
				showLog(e)
				throw IOException("Error request ${call.request().url}: ${e.message}")
			}

			override fun onResponse(call: Call, response: Response) {
				showLog(response)
				callback(response)
			}
		})
	}

	fun checkAndRequestPermissions(activity: Activity?, PERMISSIONS: Array<String?>) {
		for (permission in PERMISSIONS) {
			if (ActivityCompat.checkSelfPermission(
					activity!!, permission!!
				) != PackageManager.PERMISSION_GRANTED
			) {
				ActivityCompat.requestPermissions(
					activity, PERMISSIONS, 10
				)
				return
			}
		}
	}
}